<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
class Login extends Controller{
    //手机号登陆
    public function authLogin()
    {
        $code = input('code');//o0grz5C7YFAyziNapVnl3h7Ju8G4
        $conifg = config('wx');
        $appid = $conifg['appid'];
        $secret = $conifg['appsecrt'];
        if (!$code) {
            return json(['code'=>1,'msg'=>'缺少code参数！']);
        }
        if (!$appid || !$secret) {
            return json(['code'=>1,'msg'=>'参数错误！']);
        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        //code换取openid
//        $res = '{"session_key":"qYd+gsySyyqLnXj7nmtrBQ==","openid":"o0grz5C7YFAyziNapVnl3h7Ju8G4"}';
        $res = $this->getcurl($url);
        $arrses = json_decode($res,true);
        $openid = $arrses['openid'];//oXf6o5XwGwkFgQr_iP7BWmj9_Bu4
        if (!$openid) {
            return json(['code'=>1,'msg'=>'缺少参数openid！']);
        }
        //检测用户的openid是否存在不存在就添加 avatar
        $user_info = Db::name('admin_user')->field('id,avatar,nickname,role,leve,username')->where('openid',trim($openid))->find();
        if (!empty($user_info)) {
            $token = base64_encode(rand(111111,999999).$user_info['id'].time());
            $user_info['token'] = $token;
            db('admin_user')->where('id='.$user_info['id'])->setField(array('token'=>$token));
            $url = 'http://'.$_SERVER['HTTP_HOST'];
            $pathsasa=str_replace('\\','',get_avatar($user_info['id']));
            $pathsasa=str_replace('//','/',$pathsasa);
            $cc = $url.$pathsasa;
            $user_info['avatar'] = $cc;
            //同时 算出他的vip技术时间
            $user_info['session_key'] = $arrses['session_key'];
            return json(['code'=>0,'userinfo'=>$user_info]);
        }else{
            $data = [];
            $nickname = input('post.nickName');
//            $gender = input('post.gender/d');
            $avatarUrl = input('post.avatarUrl');
            if(empty($nickname) || empty($avatarUrl)){
                return json(['code'=>1,'msg'=>'缺少参数！']);
            }
            //新注册的话 如果有puid  也就是上级的hauler 做记录
            $data['username'] = 'aa'.rand(111111111,999999999);
            $data['nickname'] = $nickname;
            $data['avatar'] = $this->pics($avatarUrl);//头像
            $data['openid'] = $openid;
            $data['status'] = 1;
            $data['role'] = 6;
            $data['leve'] = 0;
            $data['create_time'] = time();
            $res = Db::name('admin_user')->insertGetId($data);
            if ($res) {
                $token = base64_encode(rand(1111111,9999999).$res.time());
                $url = 'http://'.$_SERVER['HTTP_HOST'];
                $pathsasa=str_replace('\\','',get_avatar($res));
                $pathsasa=str_replace('//','/',$pathsasa);
                $cc = $url.$pathsasa;
                $data['avatar'] = $cc;
                $array111['token'] = $token;
                db('admin_user')->where('id='.$res)->setField($array111);
                $info['session_key'] = $arrses['session_key'];
                return json(['code'=>0,'userinfo'=>$info]);
            }else{
                return json(['code'=>1,'msg'=>'授权失败！']);
            }
        }
    }

    protected function getcurl($url)
    {
        $ch = curl_init();
        curl_setopt ($ch,CURLOPT_URL,$url);
        curl_setopt ($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt ($ch,CURLOPT_TIMEOUT,30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 设置是否检查服务器端的证书
        $content=curl_exec($ch);
        $status=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE );
        if($status==404)
        {
            return  "";
        }
        curl_close($ch);
        return $content;
    }


    public function GrabImage($url, $filename = "")
    {
        $header = array(
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
            'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Accept-Encoding: gzip, deflate',);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);// 设置是否检查服务器端的证书
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $data = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if ($code == 200) {//把URL格式的图片转成base64_encode格式的！
            $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
            $img_content = $imgBase64Code;//图片内容
//        echo $img_content;exit;
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result))
            {

                $path = 'uploads/images/icon/'.date('Ymd');
                if(!is_dir('./'.$path)){
                    mkdir('./'.$path,0777,true);
                }

                $new_file = $path.'/'.time().rand(111111111,999999999) . '.png';
                //如果路径不存在 就创建路径


                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content))))
                {
                    return $new_file;
                }
            }
            return $filename;//返回新的文件名
        }else{
            return '1529665150703965928.png';//返回新的文件名
        }
    }

    function pics($wxicon)
    {


//        $wxicon = 'https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIdjl94MuJZExW8iboKrseHusG5LCHAskzkDQjh1rXTqvk49Feyef8deLHOkDJfkHHf5z7mibuksiaLA/132';
        //将网络图片 存到本地
        $img = $this->GrabImage($wxicon);

        $info['path'] = $img;
        $info['url'] = $wxicon;
        $pics = Db::name('admin_attachment')->where(['url'=>$wxicon])->find();
        if(!empty($pics)){
            $mtass = $pics['id'];
        }else{
            $mtass = Db::name('admin_attachment')->insertGetId($info);
        }

        return $mtass;
    }

}